package admin

import (
	"context"
	"encoding/json"
	"gozerogateway/common/errorx"
	"gozerogateway/rpc/admin/adminclient"
	"strconv"

	"gozerogateway/api/internal/svc"
	"gozerogateway/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAdminInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminInfoLogic {
	return &AdminInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminInfoLogic) AdminInfo() (resp *types.UserInfoResp, err error) {
	// todo: add your logic here and delete this line

	// 这里的key和生成jwt token时传入的key一致
	//获取jwt token中自定义参数
	userId, _ := l.ctx.Value("userId").(json.Number).Int64()
	res, err := l.svcCtx.Admin.AdminInfo(l.ctx, &adminclient.UserInfoReq{
		UserId: userId,
	})

	if err != nil {
		logx.WithContext(l.ctx).Errorf("根据userId: %s,查询用户异常:%s", strconv.FormatInt(userId, 10), err.Error())
		return nil, errorx.NewDefaultError("查询用户失败")
	}
	return &types.UserInfoResp{
		Id:           res.Id,
		Avatar:       res.Avatar,
		Name:         res.Name,
		Roles:        res.Roles,
		Introduction: res.Introduction,
	}, nil
}
